const axios = require("axios");
const md5 = require("blueimp-md5");

const param = {
  app_id: "a5f16d00b85edd",
  publisherKey: "01b243a2ab8aa7640029acda2496d276cba2182d",
};

const timestamp = new Date().getTime();
const url = "/v2/fullreport";

const instance = axios.create();
instance.defaults.baseURL = "https://openapi.toponad.com";

instance.request({
  url,
  headers: {
    "X-Up-Key": param.publisherKey,
    "X-Up-Timestamp": timestamp,
    "X-Up-Signature": sign(
      buildSignString(
        "GET",
        md5(""),
        `X-Up-Key:${param.publisherKey}\nX-Up-Timestamp:${timestamp}`,
        url
      )
    ),
  },
});

/**
 *
 * @param {string} HTTPMethod HTTP 请求的方法名称，全部大写	PUT、GET、POST 等
 * @param {string} ContentMD5 HTTP 请求中 Body 部分的 MD5 值（必须为大写字符串）875264590688CA6171F6228AF5BBB3D2
 * @param {string} ContentType HTTP 请求中 Body 部分的类型 application/json
 * @param {string} Headers 除X-Up-Signature的其它header公共参数，每个键值对之间需换行符分割，每个键值对按Key字典序升序排列
 * @param {string} Resource 由 HTTP 请求资源构造的字符串(如果有querystring不要加上），即请求URL的相对路径	/v1/fullreport
 * @returns
 */
function buildSignString(
  HTTPMethod,
  ContentMD5,
  Headers,
  Resource,
  ContentType = "application/json"
) {
  return `${HTTPMethod}\n${ContentMD5}\n${ContentType}\n${Headers}\n${Resource}`;
}

function sign(str) {
  return md5(str).toUpperCase();
}
